package 尚硅谷;

/**
 * @author zhangmin
 * @create 2022-03-22 15:11
 *
 * 单例模型：
 * 1、可以使用synchronized--代价太高
 * 2、使用Volatile--DCL模式
 */
public class SingletonDemo {

    private static volatile SingletonDemo instance=null;

    private SingletonDemo(){
        System.out.println(Thread.currentThread().getName()+"\t 构造方法执行");
    }
    public static SingletonDemo getInstance(){
        //DCL模式，在同步代码段前后各判断一次
        if (instance==null){
            synchronized (SingletonDemo.class){
                if (instance==null){  //
                    instance=new SingletonDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        //检查是否只实例化了一次--只输出一次构造方法--在单线程下可行
        System.out.println(SingletonDemo.getInstance()==SingletonDemo.getInstance());
        System.out.println(SingletonDemo.getInstance()==SingletonDemo.getInstance());
        System.out.println(SingletonDemo.getInstance()==SingletonDemo.getInstance());

        //多线程并发后(可能需要到1w个线程才会出现)：
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                SingletonDemo.getInstance();
            },String.valueOf(i)).start();
        }
    }
}
